package com.qf.shiro;

import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlAlterUserStatement;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.springframework.beans.factory.annotation.Autowired;

import javax.swing.plaf.basic.BasicTreeUI;
import java.util.Set;

/**
 * @author 金园
 * @create 2022/5/16
 * @Description
 * @className AdminAuthorizingRealm
 * @packageName com.qf.shiro
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService adminService;
    @Autowired
    DtsRoleService roleService;
    @Autowired
    DtsPermissionService permissionService;
    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取认证成功后存在session的对象
        DtsAdmin admin = (DtsAdmin) principals.getPrimaryPrincipal();
        //获取该admin对应的角色ID
        Integer[] roleIds = admin.getRoleIds();
        //根据角色id获取，角色信息
        Set<String> roles = roleService.findRoleById(roleIds);
        //根据角色id获取权限信息
        Set<String> permission = permissionService.findPermById(roleIds);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permission);
        return authorizationInfo;
    }

    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal();
        //获取密码
        String password = new String((char[]) token.getCredentials());
        //根据用户名获取用户数据
        DtsAdmin admin = adminService.findByUsername(username);
        //验证
        if (token == null){
            throw new UnknownAccountException("未知账户");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (admin.getPassword() ==   null || !passwordEncoder.matches(password,admin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        //如果delete为1表示已经被逻辑删除
        if (admin.getDeleted()){
           throw new LockedAccountException("账户被锁定");
        }
                                        //参数1：用户参数；参数2：密码；参数3：真实姓名
        return new SimpleAuthenticationInfo(admin,password,admin.getUsername());
    }
}
